<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="物料" prop="fkItemUuid">
        <el-input
          v-model="queryParams.fkItemUuid"
          placeholder="请输入物料"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="fkStockUuid">
        <el-input
          v-model="queryParams.fkStockUuid"
          placeholder="请输入仓库"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓位" prop="fkStockPosUuid">
        <el-input
          v-model="queryParams.fkStockPosUuid"
          placeholder="请输入仓位"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleCloseAccounts"
          v-hasPermi="['wms:closeAccounts:add']"
        >结账</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wms:closeAccounts:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="closeAccountsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="期间" align="center" prop="closeAccountsPeriod" />
      <el-table-column label="物料" align="center" prop="fkItemUuid" />
      <el-table-column label="仓库" align="center" prop="fkStockUuid" />
      <el-table-column label="仓位" align="center" prop="fkStockPosUuid" />
      <el-table-column label="期初" align="center">
        <el-table-column label="数量" align="center" prop="beginPeriodQty" />
        <el-table-column label="单价" align="center" prop="beginPeriodPrice" />
        <el-table-column label="金额" align="center" prop="beginPeriodAmount" />
      </el-table-column>
      <el-table-column label="本期收入" align="center">
        <el-table-column label="数量" align="center" prop="currentIncomeQty" />
        <el-table-column label="单价" align="center" prop="currentIncomePrice" />
        <el-table-column label="金额" align="center" prop="currentIncomeAmount" />
      </el-table-column>
      <el-table-column label="本期发出" align="center">
        <el-table-column label="数量" align="center" prop="currentOutcomeQty" />
        <el-table-column label="单价" align="center" prop="currentOutcomePrice" />
        <el-table-column label="金额" align="center" prop="currentOutcomeAmount" />
      </el-table-column>
      <el-table-column label="期末" align="center">
        <el-table-column label="数量" align="center" prop="endPeriodQty" />
        <el-table-column label="单价" align="center" prop="endPeriodPrice" />
        <el-table-column label="余额" align="center" prop="endPeriodAmount" />
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:closeAccounts:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:closeAccounts:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改结账管理对话框 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="仓库" prop="fkStockUuid">
          <el-input v-model="form.fkStockUuid" v-show="false"/>
          <el-input placeholder="请点击右侧按钮选择仓库" readOnly="true" v-model="form.selectedStock" class="input-with-select"
                    :style="{width: '100%'}">
            <el-button type="info" plain
                       @click="dialog_show_stock"
                       slot="append" icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <select-stock ref="component_selectStock" @ok="selectStock_done" />
  </div>


</template>

<script>
import { listCloseAccounts, getCloseAccounts, delCloseAccounts, addCloseAccounts, updateCloseAccounts } from "@/api/wms/closeAccounts";
import selectStock from "../../wms/stock/selectStock";
import {listStockIn} from "@/api/wms/stockIn";
import {  updateAllStock,listStock,listStockUuid } from "@/api/wms/stock";
import { listWmsInventory } from "@/api/wms/inventorySheet";
import { listInitDate } from "@/api/wms/initDate";
import {getNextMonth} from "../../../utils/request";
import {addLastDate, listLastDate} from "../../../api/wms/lastDate";

export default {
  name: "CloseAccounts",
  components:{ selectStock},

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 结账管理表格数据
      closeAccountsList: [],
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        closeAccountsYear: null,
        closeAccountsPeriod: null,
        fkItemUuid: null,
        fkStockUuid: null,
        fkStockPosUuid: null,
        beginPeriodQty: null,
        beginPeriodPrice: null,
        beginPeriodAmount: null,
        currentIncomeQty: null,
        currentIncomePrice: null,
        currentIncomeAmount: null,
        currentOutcomeQty: null,
        currentOutcomePrice: null,
        currentOutcomeAmount: null,
        endPeriodQty: null,
        endPeriodPrice: null,
        endPeriodAmount: null,
      },
      params:{
        startDate:null,
        endDate:null
      },
      // 表单参数
      form: {},
      form_stock: {
        list:[],
      },
      // 表单校验
      rules: {
        closeAccountsYear: [
          { required: true, message: "年不能为空", trigger: "blur" }
        ],
        closeAccountsPeriod: [
          { required: true, message: "期间不能为空", trigger: "blur" }
        ],
        fkItemUuid: [
          { required: true, message: "物料id不能为空", trigger: "blur" }
        ],
        fkStockUuid: [
          { required: true, message: "仓库id不能为空", trigger: "blur" }
        ],
        fkStockPosUuid: [
          { required: true, message: "仓位id不能为空", trigger: "blur" }
        ],
        beginPeriodQty: [
          { required: true, message: "期初数量不能为空", trigger: "blur" }
        ],
        beginPeriodPrice: [
          { required: true, message: "期初单价不能为空", trigger: "blur" }
        ],
        beginPeriodAmount: [
          { required: true, message: "期初金额不能为空", trigger: "blur" }
        ],
        currentIncomeQty: [
          { required: true, message: "本期收入不能为空", trigger: "blur" }
        ],
        currentIncomePrice: [
          { required: true, message: "收入单价不能为空", trigger: "blur" }
        ],
        currentIncomeAmount: [
          { required: true, message: "收入金额不能为空", trigger: "blur" }
        ],
        currentOutcomeQty: [
          { required: true, message: "本期支出不能为空", trigger: "blur" }
        ],
        currentOutcomePrice: [
          { required: true, message: "支出单价不能为空", trigger: "blur" }
        ],
        currentOutcomeAmount: [
          { required: true, message: "支出金额不能为空", trigger: "blur" }
        ],
        endPeriodQty: [
          { required: true, message: "期末数量不能为空", trigger: "blur" }
        ],
        endPeriodPrice: [
          { required: true, message: "期末单价不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建者不能为空", trigger: "blur" }
        ],
        endPeriodAmount: [
          { required: true, message: "期末余额不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询结账管理列表 */
    getList() {
      this.loading = true;
      listCloseAccounts(this.queryParams).then(response => {
        this.closeAccountsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        closeAccountsUuid: null,
        closeAccountsYear: null,
        closeAccountsPeriod: null,
        fkItemUuid: null,
        fkStockUuid: null,
        fkStockPosUuid: null,
        beginPeriodQty: null,
        beginPeriodPrice: null,
        beginPeriodAmount: null,
        currentIncomeQty: null,
        currentIncomePrice: null,
        currentIncomeAmount: null,
        currentOutcomeQty: null,
        currentOutcomePrice: null,
        currentOutcomeAmount: null,
        endPeriodQty: null,
        endPeriodPrice: null,
        createBy: null,
        endPeriodAmount: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        initDate: null
      };

      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.closeAccountsUuid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleCloseAccounts() {
      /**判断是否存在结账数据，查询初始化表*/
      this.queryParams.wmsDictStockInType = '3'
      this.queryParams.oaDictConfirmStatus = 'pass'
      listStockIn(this.queryParams).then(response => {
        this.stockInList = response.rows;
        console.log(this.stockInList)
        /**如果存在结账数据*/
        if(this.stockInList.length>0){
          console.log("111")
          /**修改仓库状态为结帐中*/
          updateAllStock({stockList:this.stockList,sysNormalDisable:"结帐中"}).then(response => {
          });
          /**查询所有单据是否审核完成*/
          listWmsInventory({edit:'editing',reject:'reject',wait:'waiting'}).then(response=>{
            console.log(response)
            this.confirmedList = response.rows;
            console.log( this.confirmedList )
            /**如果查询结果大于零 则存在未审核单据，需要审核后才能结账*/
            if(this.confirmedList.length>0){
              this.ids = this.confirmedList.map(item => item.docNum)
              this.$modal.msgError("结账失败,存在未审核的单据,单据编号为"+this.ids)
              /**修改仓库状态为正常*/
              updateAllStock({sysNormalDisable:0}).then(response => {
              });
            }else{
              /**如果查询结果无数据 则可以进行结账操作*/
              console.log("0000000000")
              /**判断结账日期表中是否结过帐*/
              listLastDate(this.queryParams).then(response => {
                this.lastDateList = response.rows;
                console.log(this.lastDateList)
                /**如果结帐表中存在数据，则取最近日期为本期期初日期，期末日期加一个月*/
                if(this.lastDateList[0]!=null){
                  console.log("lastDate")
                  this.params.startDate=this.lastDateList[0].lastDate
                  this.params.endDate=getNextMonth(this.lastDateList[0].lastDate)
                  this.form.year = this.params.endDate.substring(0,4)
                  this.form.month = this.params.endDate.substring(5,7)
                  this.form.day = this.params.endDate.substring(8,10)
                  addLastDate(this.form).then(response => {
                  });
                }else{
                  /**如果结帐表中没数据，则取期初表中数据为期初日期，期末日期加一个月*/
                  console.log("initDate")
                  listInitDate(this.queryParams).then(response => {
                    this.initDateList = response.rows;
                    console.log(this.initDateList[0].initDate)
                    this.params.startDate = this.initDateList[0].initDate;
                    this.params.endDate = getNextMonth(this.initDateList[0].initDate)
                    this.form.year = this.initDateList[0].year
                    this.form.month = this.initDateList[0].month
                    this.form.day = this.initDateList[0].day
                    addLastDate(this.form).then(response => {
                    });
                  });
                }
              });
            }
          });
        }else{
          this.$modal.msgError("结账失败，没有结账数据");
        }
      });
      this.open = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const closeAccountsUuid = row.closeAccountsUuid || this.ids
      getCloseAccounts(closeAccountsUuid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改结账管理";
      });
    },
    /** 提交按钮 */
    submitForm() {

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const closeAccountsUuids = row.closeAccountsUuid || this.ids;
      this.$modal.confirm('是否确认删除结账管理编号为"' + closeAccountsUuids + '"的数据项？').then(function() {
        return delCloseAccounts(closeAccountsUuids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wms/closeAccounts/export', {
        ...this.queryParams
      }, `wms_closeAccounts.xlsx`)
    },
    /** 显示对话框：选择仓库 */
    dialog_show_stock() {
      this.$refs.component_selectStock.dialog_show_stock();
    },

    /** 完成：选择仓库*/
    selectStock_done(stock) {
      console.log(stock)
      this.form.fkStockUuid = stock.stockUuid
      this.form.selectedStock = `${stock.stockName}(${stock.stockCode})`
      this.form.stockUuid = stock.stockUuid,
        console.log(this.form.stockUuid)
    },
  }
};
</script>
